#include "Renderer/GUIWindowRendererManager.h"
#include "GUIError.h"
#include "GUIBase.h"
#include "Renderer/GUIWindowRenderer.h"

namespace YGUI
{
    template<>
    WindowRendererManager* Singleton<WindowRendererManager>::m_singleton = NULL;

    WindowRendererManager::WindowRendererManager(void)
    {
        initDefaultRenderer();
    }

    WindowRendererManager::~WindowRendererManager(void)
    {
    }

    WindowRendererManager& WindowRendererManager::getSingleton(void)
    {
        static WindowRendererManager instance;
        return *m_singleton;
    }

    WindowRendererManager* WindowRendererManager::getSingletonPtr(void)
    {
        if(!m_singleton)
            getSingleton();
        return m_singleton;
    }

    bool WindowRendererManager::isFactoryExits(const String &name) const
    {
        return (m_rendererFactories.end() != m_rendererFactories.find(name));
    }

    RendererFactory* WindowRendererManager::getFactory(const String &name) const
    {
        RendererList::const_iterator it = m_rendererFactories.find(name);
        if(it == m_rendererFactories.end())
        {
            throw Exception("WindowRendererManager::getFactory--Specified class factory is not exists: %s", name.c_str());
        }
        else return it->second;
    }

    void WindowRendererManager::addFactory(RendererFactory* factory)
    {
        if(factory == NULL)
            return;
        if(!m_rendererFactories.insert(std::make_pair(factory->getName(), factory)).second)
        {
            return;
        }
    }

    void WindowRendererManager::removeFactory(const String& name)
    {
        m_rendererFactories.erase(name);
    }

    WindowRenderer* WindowRendererManager::createWindowRenderer(const String& name)
    {
        RendererFactory* factory = getFactory(name);
        return factory->createRenderer();
    }

    void WindowRendererManager::destroyWindowRenderer(YGUI::WindowRenderer* wr)
    {
        RendererFactory* factory = getFactory(wr->getName());
        factory->destroy(wr);
    }
};